<template>
    <div>
        <div class="search-form">
            <el-form :model="searchForm" :rules="rules" inline>
                <el-form-item label="课堂ID">
                    <el-input v-model="searchForm.classID" @keyup.enter="search" placeholder="请输入课堂ID"></el-input>
                </el-form-item>
                <el-form-item label="课堂姓名">
                    <el-input v-model="searchForm.className" @keyup.enter="search" placeholder="请输入课堂姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-button class="import-el-button" @click="downLoadStu()">下载课堂列表</el-button>
        <el-table ref="multipleTableRef" :data="displayedClass" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />

            <el-table-column property="className" label="课堂名称" />
            <el-table-column property="classID" label="课堂ID" />
            <el-table-column property="courseID" label="课程ID" />
            <el-table-column property="teacherID" label="教师ID" show-overflow-tooltip />
            <el-table-column label="操作" width="360">
                <template #default="{ row }">
                    <router-link :to="'/classDetail/' + row.classID" @click="findDetail(row)">查看详情</router-link>
                    <el-button link type="primary" style="margin-top: 0px;" size="small"
                        @click="editPerson(row)">编辑</el-button>
                    <el-dialog title="编辑课堂信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="课堂名称" :label-width="formLabelWidth">
                                <el-input v-model="form.className" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="课堂ID" :label-width="formLabelWidth">
                                <el-input v-model="form.classID" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="教师ID" :label-width="formLabelWidth">
                                <el-input v-model="form.teacherID" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="课程ID" :label-width="formLabelWidth">
                                <el-input v-model="form.courseID" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    確定
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <!-- <el-button link type="primary" size="small" @click="deleteSingleTeacherFun(row)">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="classData.length">
        </el-pagination>
        <div style="margin-top: 20px">
            <el-button @click="deleteBatchTeacher">批量删除</el-button>
        </div>
    </div>
</template>
  
<script setup>
import { ref, toRefs, reactive, computed, watch, onMounted } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../store'
import { ElTable, ElUpload } from 'element-plus'
import { editorClassInfo, findallStudentByClass, findallTeacherByClass, selectCourse, findallTAByClass, allClassInfoService } from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
const router = useRoute();
const store = useStore()
const fileList = ref()
const searchForm = ref({
    classID: '',
    className: ''
});
watch(
    () => store.classList,
    () => classData.value = store.classList,
    { deep: true }
)
const classData = ref(store.classList);
const form = ref({
    classID: '',
    className: '',
    teacherID: '',
    courseID: '',
    editIndex: 0
});
const displayedClass = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedClass.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedClass.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return classData.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedClass.value = paginateData();
})
// const addForm = ref({
//     className: '',
//     classID: ''
// });
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    const data = {
        className: addForm.value.className,
        classID: addForm.value.classID,
        password: '1234'
    };
    displayedClass.value.push(data)
    addForm.value = {}
    await addSingleStudent(data)
};
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
    const data = []
    selectionRow.value.map((item, index) => {
        data.push(item.classID)
        classData.value.map((list, idx) => {
            if (item.classID === list.classID)
                displayedClass.value.splice(idx, 1)
        })
    })
    await deleteBatchStudents(data)
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.className = row.className;
    form.value.classID = row.classID;
    form.value.courseID = row.courseID;
    form.value.teacherID = row.teacherID;
    dialogFormVisible.value = true;
}
//删除单个老师
const deleteSingleTeacherFun = async (row) => {
    const index = classData.value.findIndex(item => item.classID === row.classID);
    displayedClass.value.splice(index, 1)
    await deleteSingleStudent(row.classID)
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        className: form.value.className,
        courseID: form.value.courseID,
        teacherID: form.value.teacherID,
        classID: form.value.classID
    }
    await editorClassInfo(data)
    const index = classData.value.findIndex((item) => item.classID === form.value.classID)
    classData.value[index].className = form.value.className
}
//查看详情
const findDetail = async (data) => {
    store.setDetailClass(data)
    const res = await findallStudentByClass(data.classID)
    store.setAllStudentInClass(res.data)
    const res2 = await findallTeacherByClass(data.classID)
    store.setAllTeacherInClass(res2)
    const res3 = await findallTAByClass(data.classID)
    store.setAssistantList(res3)

}
const resetForm = () => {
    searchForm.value.classID = '';
    searchForm.value.className = '';
};
const search = async () => {
    let result={
        classID:searchForm.value.classID,
        className:searchForm.value.className,
        pageSize:20,
        pageNum:1
    }
    const res = await allClassInfoService(result)
    displayedClass.value = res.data
    classData.value=res.data
    
};


const handleCloseDialog = (done) => {
    form.value.classID = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactiveclassData } = toRefs(classData);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(classData.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'class.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        classData.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, classID, className] = row;
            return { id, classID, className };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script>
  
<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}

.import-el-button {
    width: fit-content;
}
</style>
  
  <!-- 引入 Element Plus 组件库 -->